package com.team.mpc.service.mq;

import com.team.mpc.service.impl.LocalServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@RocketMQTransactionListener(txProducerGroup = "tx_p")
public class SendMsgListener implements RocketMQLocalTransactionListener {
    @Autowired
    private LocalServiceImpl localService;
    //执行本地事务  message为发送的消息，object为发送事务消息时传入的第四个参数
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        Object txId = message.getHeaders().get("txId");
        try {
            localService.doSomeThing();
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    //消息回查   如果指定时间mq没收到事务的确认，mq会进行回查，调用该方法
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        Object txId = message.getHeaders().get("txId");
        log.info("根据txId查询本地事务是否已经完成");
        if (txId !=null){
            log.info("已经完成");
            return RocketMQLocalTransactionState.COMMIT;
        }else{
            log.info("未完成");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
